package com.wenlei.servlet;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JndiJDBCServlet extends HttpServlet {

    @Override
    public void service( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
        PrintWriter writer = response.getWriter();
        StringBuilder stringBuilder = new StringBuilder();
        try {
            Context context = new InitialContext();
            Context envContext = (Context) context.lookup( "java:comp/env" );
            DataSource dataSource = (DataSource) envContext.lookup( "jdbc/geekbang" );
            try ( Connection connection = dataSource.getConnection() ) {
                PreparedStatement    preparedStatement = connection.prepareStatement( "SELECT Table_schema,table_name,create_time FROM information_schema.`TABLES` LIMIT 1;" );
                ResultSet resultSet = preparedStatement.executeQuery();
                stringBuilder.append( "从information_schema.`TABLES`中取出一条数据: </br>" );
                while ( resultSet.next() ) {
                    stringBuilder.append( "  Table_schema =" ).append( resultSet.getString( "Table_schema" ) ).append( "</br>" );
                    stringBuilder.append( "  table_name =" ).append( resultSet.getString( "table_name" ) ).append( "</br>" );
                    stringBuilder.append( "  create_time =" ).append( resultSet.getString( "create_time" ) ).append( "</br>" );
                }
                resultSet.close();
                preparedStatement.close();
            } catch ( SQLException throwables ) {
                throwables.printStackTrace();
            }
        } catch ( NamingException e) {
            e.printStackTrace();
        }
        println( writer, stringBuilder.toString() );
    }

    private static void println( Writer writer, Object message ) throws IOException {
        writer.write( String.format( "[线程 - %s] : %s\n", Thread.currentThread().getName(), message ) );
        writer.flush();
    }
}